package com.uitl;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;

import java.util.Date;

/**
 * @author
 * @create 2020-11-11 21:16
 */
public class JwtUitl {

    //定义Jwt的基础数据，也可以写在配置文件中
    private static final String SECRET = "abc";  //盐值(密钥)
    private static final long EXPIRE = 1000*60*30;
    private static final String ISSUSER = "ljw";  //签发人

    //生成token的方法
    public static String create(String username){
        //设置加密的算法
        Algorithm algorithm = Algorithm.HMAC256(SECRET);
        Date date = new Date();
        //指定过期时间
        Date expire = new Date(date.getTime()+EXPIRE);
        //生成Jwt
        String jwt = JWT.create()
                .withIssuer(ISSUSER)
                .withIssuedAt(date)
                .withExpiresAt(expire)
                .withClaim("username",username)
                .sign(algorithm);
        return jwt;
    }

    //验证方法
    public static boolean verify(String token){
        //验证成功
        try {
            //加密的盐值
            Algorithm algorithm = Algorithm.HMAC256(SECRET);
            //获取验证器
            JWTVerifier verifier = JWT.require(algorithm).
                    withIssuer(ISSUSER).build();
            //没有异常及验证成功
            verifier.verify(token);
            return true;
        }catch (Exception e){
            //验证失败
            e.printStackTrace();
            return false;
        }
    }

    //获取输入的名字
    public static String getUserName(String token){
        return JWT.decode(token).getClaim("username").asString();
    }

    //判断token是否过期
    public static boolean Expire(String token){
        Date now = new Date();
        //获取过期时间
        Date expire = JWT.decode(token).getExpiresAt();
        return now.after(expire);
    }

}
